<template>
    <el-main v-loading="showLoading">
		<el-form ref="actionform" :model="formData" label-width="80px">
			<el-form-item label="权益类型" verify prop="medalEquityType">
				<el-select
                    v-model="formData.medalEquityType"
					class="formItem"
                    placeholder="请输入权益类型">
                    <el-option
                        v-for="item in medalEquityTypeList"
                        :key="item.labelId"
                        :label="item.labelText"
                        :value="item.labelId"></el-option>
                </el-select>
			</el-form-item>
			<el-form-item label="权益标题" verify prop="medalEquityTitle">
				<el-input class="formItem" v-model="formData.medalEquityTitle" placeholder="请输入权益标题"></el-input>
			</el-form-item>
			<el-form-item label="权益描述" verify prop="medalEquityName">
				<el-input class="formItem" v-model="formData.medalEquityName" placeholder="请输入权益描述"></el-input>
			</el-form-item>
			<el-form-item label="红包金额" verify prop="redPacket" v-if="!formData.medalEquityType">
				<el-select
					v-model="formData.redPacket"
					multiple
					collapse-tags
					placeholder="请选择红包"
					class="formItem">
					<el-option
						v-for="item in redPacketList"
						:key="item.redPacketUid"
						:label="item.redPacketName"
						:value="item.redPacketUid">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="关联商品" prop="bindProducts" verify v-else>
				<div class="formItem temps" @click="handleActions" v-if="!relationGoodsList.length">
					请选择关联商品
				</div>
				<div v-else>
					<el-select
						v-model="bindProducts"
						multiple
						collapse-tags
						@change="goodsChange"
						placeholder="请选择关联商品"
						class="formItem">
						<el-option
							v-for="item in relationGoodsList"
							:key="item.productUid"
							:label="item.productName"
							:value="item.productUid">
						</el-option>
					</el-select>
					<el-button @click="handleActions">更多</el-button>
				</div>
			</el-form-item>
			<el-form-item label="权益图片" prop="medalEquityImageUrl" verify>
				<el-upload
					:action="uploadUrl"
					:data="access_token"
					:show-file-list="false"
					:before-upload="$util.beforeUpload"
					:on-success="uploadMedalImageSuccess"
				>
					<el-image :src="formData.medalEquityImageUrl" class="avatar" v-if="formData.medalEquityImageUrl" />
					<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					<el-input class="inputs none imgArea" v-model="formData.medalEquityImageUrl"></el-input>
				</el-upload>
			</el-form-item>
			<el-form-item class="flex-center" style="margin: 30px 0 0">
				<el-button type="primary" @click="handlePost">确  认</el-button>
				<el-button @click="closeDialog">取  消</el-button>
			</el-form-item>
		</el-form>
    </el-main>
</template>

<script>
    import {
		addRights,
		editRights
    } from "@/api/table";

    export default {
        name: "MEDAL_RIGHTS_ACTION",
        components: {},
        props: {
            infoData: {
            	type: Object,
                default() {
					return {}
				}
			},
			goodsDataList: {
				type: Array,
                default() {
					return []
				}
			},
			redPacketList: {
				type: Array,
                default() {
					return []
				}
			},
			relationGoods: {
				type: Array,
                default() {
					return []
				}
			},
			medalEquityTypeList: {
				type: Array,
                default() {
					return []
				}
			},
		},
        data() {
            return {
				formData: this.infoData,
				showLoading: false,
				bindProducts: [],
				redPacket: [],
				relationGoodsList: [],        
				access_token: {
                    access_token: this.$store.getters.token
                },
				uploadUrl: process.env[this.$base] + "/medias/image/upload",
            }
		},
		watch: {
			relationGoods(newVal, oldVal) {
				const bindProductsArray = [];
				newVal.map(item => {
					return bindProductsArray.push(item.productUid)
				});
				this.relationGoodsList = newVal;
				this.$set(this.formData, 'bindProducts', bindProductsArray)
				this.bindProducts = bindProductsArray;
			},
			goodsDataList(newVal, oldVal) {
				return newVal
			}
		},
      	methods: {
			updateData() {
				const { medalRightItems, medalEquityType } = this.infoData;
				const bindProductsArray = [];
				medalRightItems.map(item => {
					if (medalEquityType === 1) {
						return bindProductsArray.push(item.productUid)
					}
					return bindProductsArray.push(item.redPacketUid)
				});

				if (medalEquityType === 1) {
					const dataArray = [];
					this.goodsDataList.map(item => {
						bindProductsArray.map(i => {
							if (item.productUid === i) {
								return dataArray.push(item);
							}
						})
					});
					this.relationGoodsList = dataArray;
				}

				this.bindProducts = bindProductsArray;
				this.formData = this.infoData;
				const medalEquityTypeNames = medalEquityType === 1 ? 'bindProducts' : 'redPacket';
				this.$set(this.formData, medalEquityTypeNames, bindProductsArray);
			},

			// 上传图片
			uploadMedalImageSuccess(response, file, fileList) {
				if (response.code == "200") {
					const { fileUrl, fileUid } = response.data;
					this.$set(this.formData, 'medalEquityImageUrl', fileUrl);
				}
			},

			// 下拉框change
			goodsChange(e) {
				this.$set(this.formData, 'bindProducts', e)
			},
			
			// 关联商品
			handleActions() {
				this.$event.emit('ShowRelatedProducts', this.relationGoodsList)
			},

			getMedalEquityName(id, type) {
				if (type) {
					return this.relationGoodsList.find(item => item.productUid === id) || {}
				}
				return this.redPacketList.find(item => item.redPacketUid === id) || {};
			},

			// 确认
			handlePost() {
				let medalRightItems = [];
				const {
					medalEquityTitle,
					medalEquityName,
					medalEquityType,
					medalEquityUid,
					medalEquityImageUrl
				} = this.formData;
				if (medalEquityType) {
					if (!this.bindProducts.length) {
						this.$message.info('请选择关联商品！')
						return
					}
					this.bindProducts.map(item => {
						const info = this.getMedalEquityName(item, medalEquityType);
						return medalRightItems.push({
							productUid: item,
							redPacketUid: null,
							medalEquityCount: 1,
							medalEquityImage: info.listImageUrl,
							medalEquityType,
							medalEquityName: info.productName,
						})
					})
				} else {
					this.formData.redPacket.map(item => {
						const info = this.getMedalEquityName(item, medalEquityType);
						return medalRightItems.push({
							redPacketUid: item,
							productUid: null,
							medalEquityCount: 1,
							medalEquityImage: info.redPacketCoverUrl,
							medalEquityType,
							medalEquityName: info.redPacketName,
						})
					})
				}

				const postData = {
					medalRightItems: JSON.stringify(medalRightItems), 
					medalEquityName,
					medalEquityImageUrl,
					medalEquityTitle
				}

				this.$refs.actionform.validate(valid => {
					if (valid) {
						this.showLoading = true;
						// 编辑
						if (medalEquityUid) {
							editRights({
								...postData,
								medalEquityUid
							}).then(res => {
								if (res.data.isSuccessful !== "Y") {
									this.$message.error(res.data.message);
									return
								}
								this.$message({
									message: "编辑成功！",
									type: "success"
								});
								setTimeout(() => {
									this.closeDialog(true);
								}, 0);
							}).finally(() => {
								this.showLoading = false;
							});
							return
						}

						// 新增
						addRights(postData).then(res => {
							if (res.data.isSuccessful !== "Y") {
								this.$message.error(res.data.message);
								return
							}
							this.$message({
								message: "新增成功！",
								type: "success"
							});
							setTimeout(() => {
								this.closeDialog(true);
							}, 0);
						}).finally(() => {
							this.showLoading = false;
						});
					}
				})
			},

			closeDialog(refresh = false, type = '') {
				this.formData = {};
				this.relationGoodsList = [];
				this.$emit('func', {
					action: false,
					refresh,
					type
				})
			}
      	},
  	}
</script>
<style lang="scss" scoped>
	.formItem {
		width: 360px;
    }
    .temps {
        border-radius: 4px;
		padding: 0 15px;
		color: #cccccc;
		cursor: pointer;
        border: 1px solid #DCDFE6;
	}
</style>

